package blog.controller;

import cn.hutool.core.date.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

import static cn.hutool.core.date.DatePattern.HTTP_DATETIME_PATTERN;
import static cn.hutool.core.date.DatePattern.NORM_DATETIME_PATTERN;

/**
 * @author qipan
 * @date 2019/11/29 11:31
 */
@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {

    public CookieServlet() {
    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String option = req.getParameter("op");
        System.out.println("option=" + option);

        if (option != null) {
            try {
                Method method = getClass().getDeclaredMethod(option, HttpServletRequest.class, HttpServletResponse.class);
                method.setAccessible(true);
                method.invoke(this,req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req,resp);
    }

    private void setLastAccessTime(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("setLastAccessTime()");
        String date = DateUtil.format(new Date(),"yyyy-MM-dd-hh:mm:ss");
        // System.out.println(date);
        // 创建Cookie
        Cookie cookie = new Cookie("lastAccessTime",date);
        // 发送给浏览器保存
        resp.addCookie(cookie);
    }

    private void cookieMgr(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("cookieMgr()");
        HttpSession session = req.getSession();
        Cookie lastAccessTime = getSpecifiedCookie(req, "lastAccessTime");
        Object privilege = req.getAttribute("privilege");

        System.out.println("privilege:" + privilege);

        session.setAttribute("privilege", privilege);

        if (lastAccessTime != null) {
            lastAccessTime.setValue(DateUtil.format(new Date(), "yyyy-MM-dd-HH:mm:ss"));
            resp.addCookie(lastAccessTime);
            session.setAttribute("welcome_status",lastAccessTime.getValue());
        } else {
            Cookie cookie = new Cookie("lastAccessTime",DateUtil.format(new Date(), "yyyy-MM-dd-HH:mm:ss"));
            resp.addCookie(cookie);
            session.setAttribute("welcome_status","欢迎首次访问");
        }
        req.getRequestDispatcher("/WEB-INF/success.jsp").forward(req,resp);
//        resp.sendRedirect(req.getContextPath() + "/success.jsp");
    }


    /**
     * 获取指定key值的Cookie
     * @param req 请求
     * @param key Cookie的key值
     * @return null - 不存在
     */
    private Cookie getSpecifiedCookie(HttpServletRequest req, String key) {
        Cookie[] cookies = req.getCookies();
        Cookie cookie = null;
        if ((cookies != null && cookies.length > 0)) {
            for (Cookie ck : cookies) {
                if (ck != null && ck.getName().equals(key)) {
                    cookie = ck;
                    break;
                }
            }
        }
        return cookie;
    }

    /**
     * 设置指定Cookie并写回到浏览器。如果不存在指定Cookie,就新建一个Cookie写回浏览器
     * @param resp
     * @param key
     * @param value
     */
    private void setSpecifiedCookieBack(HttpServletRequest req, HttpServletResponse resp, String key, String value) {
        Cookie cookie = getSpecifiedCookie(req, key);
        // 如果指定cookie存在,设置新值
        if (cookie != null) {
            cookie.setValue(value);
            resp.addCookie(cookie);
        } else {
            resp.addCookie(new Cookie(key,value));
        }
    }

    private String getSpecifiedCookieValue(HttpServletRequest req, String key) {
        Cookie cookie = getSpecifiedCookie(req, key);
        String cookieValue = null;
        if (cookie != null) {
            cookieValue = cookie.getValue();
        }
        return cookieValue;
    }
}
